<?php
/**
 * 機種依存文字 バリデータ
 *
 * @package	Validate
 * @subpackage	PlatformDependentCharacter
 * @author		tanaka
 */
class Validate_PlatformDependentCharacter extends Zend_Validate_Abstract
{
	const INVALID = 'Invalid';

	/**
	 * @var array
	 */
	protected $_messageTemplates = array(
		self::INVALID => 'The platform dependent character is included',
	);

	/**
	 * Encoding to use
	 *
	 * @var string|null
	 */
	protected $_encoding = null;

	/**
	 * Sets validator options
	 *
	 * @param	mixed | Zend_Config $encoding
	 * @return	void
	 */
	public function __construct($encoding = null)
	{
		if ($encoding instanceof Zend_Config) $encoding = $encoding->toArray();

		if (is_array($encoding)) {
			if (array_key_exists('encoding', $encoding)) {
				$encoding = $encoding['encoding'];
			}
			else {
				require_once 'Zend/Validate/Exception.php';
				throw new Zend_Validate_Exception("Missing option 'encoding'");
			}
		}

		$this->setEncoding($encoding);
	}

	/**
	 * Returns the actual encoding
	 *
	 * @return	string
	 */
	public function getEncoding()
	{
		return $this->_encoding;
	}

	/**
	 * Sets a new encoding to use
	 *
	 * @param	string	$encoding
	 * @return	Validate_PlatformDependentCharacter
	 */
	public function setEncoding($encoding = null)
	{
		$this->_encoding = $encoding !== null ? $encoding : mb_internal_encoding();
		return $this;
	}

	/**
	 * Defined by Zend_Validate_Interface
	 *
	 * @param	mixed	$value
	 * @return	bool
	 */
	public function isValid($value)
	{
		$this->_setValue($value);

		$sjis_win = mb_convert_encoding($value, 'sjis-win', $this->_encoding);
		$sjis = mb_convert_encoding($sjis_win, 'sjis','sjis-win');
		$sjis_win = mb_convert_encoding($sjis, 'sjis-win','sjis');
		$target = mb_convert_encoding($sjis_win, $this->_encoding, 'sjis-win');

		if ($value !== $target) {
			$this->_error(self::INVALID);
			return false;
		}

		return true;
	}
}
